#include "sqliteDataBase.h"
#include <iostream>
using namespace std;
#include <sqlite3.h>

#include <unistd.h>
#include <iomanip>
#include <vector>

stdSqliteDataBase::stdSqliteDataBase():m_db(nullptr)
{

}

stdSqliteDataBase::~stdSqliteDataBase()
{
}
bool stdSqliteDataBase::connectDB(const std::string &dbFileName)
{   
    //连接数据库
    int ret = sqlite3_open(dbFileName.c_str(),&m_db);
    if(ret != SQLITE_OK)
    {
        cout<<"sqlite3 open error"<<sqlite3_errmsg(m_db)<<endl;
        return false;
    }

    return true;
}

bool stdSqliteDataBase::execute(const std::string sql)
{
    int ret = sqlite3_exec(m_db,sql.c_str(),NULL,NULL,NULL);
    if(ret != SQLITE_OK)
    {
        cout<<"sqlite3 open error"<<sqlite3_errmsg(m_db)<<endl;
        return false;
    }

    return true;
}

vector<vector<string>> stdSqliteDataBase::query(const std::string sql)
{   
    vector<vector<string>> data;
    char **result = NULL;
    int rows = 0;
    int columns = 0;
    int ret = sqlite3_get_table(m_db,sql.c_str(),&result,&rows,&columns,NULL);
    if(ret != SQLITE_OK)
    {
        cout<<"sqlite3_get_table error:"<<sqlite3_errmsg(m_db)<<endl;
        return data;
    }

    for(int row = 1;row <= rows;row++)
    {   
        vector<string> rowData;
        for(int col = 0;col < columns;col++)
        {
            // cout <<left<<setw(16)<<result[row*columns + col];
            rowData.push_back(result[row*columns+col]);
        }
        data.push_back(rowData);
    }

    return data;
}

void stdSqliteDataBase::closeDB()
{   
    
    sqlite3_close(m_db);
}
